﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using DB = HTComics.Data;
using System.Web.Services;
using System.IO;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HTComics.Web.Common;

namespace HTComics.Web
{
    public partial class ViewIssues : System.Web.UI.Page
    {
        protected string title;
        protected int totalIssues;
        protected string cid;
        protected int pageSize = 10;

        protected void Page_Load(object sender, EventArgs e)        
        {
            cid = Request.QueryString["cid"];
            LoadData();
        }

        private void LoadData()
        {
            string cid = Request.QueryString["cid"];
            HtmlGenericControl heading;
            HtmlGenericControl div;

            DataTable dtResults = DB.Search.SearchIssues(cid);

            totalIssues = dtResults.Rows.Count;

            for (int i=0; i<= dtResults.Rows.Count-1; i++)
            {
                title = dtResults.Rows[i][0].ToString();

                heading = new HtmlGenericControl("h3");
                div = new HtmlGenericControl("div");

                heading.ID = "heading" + i;
                heading.Attributes.Add("issue", dtResults.Rows[i]["IssueNumber"].ToString());
                heading.Attributes.Add("qty", dtResults.Rows[i]["Qty"].ToString());
                div.ID = "div" + i;
                

                heading.InnerHtml = "<a href=\"#\">";
                heading.InnerHtml += "<table width=\"100%\"><tr>";
                heading.InnerHtml += "<td width=\"30%\">Issue: " + dtResults.Rows[i]["IssueNumber"].ToString() + "</td>";
                heading.InnerHtml += "<td width=\"70%\">Quantity: " + dtResults.Rows[i]["Qty"].ToString() + "</td>";
                heading.InnerHtml += "</tr></table>";
                heading.InnerHtml += "</a>";

                div.InnerHtml = "Loading ...";
                div.Style.Add("height", "100px");

                divMaster.Controls.Add(heading);
                divMaster.Controls.Add(div);
            }
        }

        [WebMethod]
        public static string GetIssue(string cid, string issue)
        {
            string tblDetails = "No Data Found";
            DataSet dsResults = DB.Search.GetIssueDetails(cid, issue,null);
            string img;
            double discount = 0;

            if (dsResults.Tables[0].Rows.Count > 0)
            {
                string imgLoc = dsResults.Tables[0].Rows[0][0].ToString()[0] + "/" + dsResults.Tables[0].Rows[0][0];

                try
                {
                    if (File.Exists(HttpContext.Current.Server.MapPath("~/Images/Covers/" + imgLoc + "/" + issue + ".jpg")))
                        img = "<a href='#'><img id='img" + issue + "' src=\"../Images/Covers/" + imgLoc + "/" + issue + ".jpg\" height='120px' width='90px' onclick=showDetails(this) border='0' cn=\"" + dsResults.Tables[0].Rows[0]["Title"] + "\" issue='" + issue + "' cp='" + dsResults.Tables[0].Rows[0]["CoverPrice"] + "' sl='" + dsResults.Tables[0].Rows[0]["Storylines"] + "' wrt='" + dsResults.Tables[0].Rows[0]["Writer"] + "' art='" + dsResults.Tables[0].Rows[0]["Artist"] + "' cd='" + Convert.ToDateTime(dsResults.Tables[0].Rows[0]["CoverDate"]).ToString("MMM yyyy") + "'/></a>";
                    else
                        img = "<a href='#'><img id='img" + issue + "' src='../Images/noimage.png' height='120px' width='90px' onclick=showDetails(this) border='0' cn=\"" + dsResults.Tables[0].Rows[0]["Title"] + "\" issue='" + issue + "' cp='" + dsResults.Tables[0].Rows[0]["CoverPrice"] + "' sl='" + dsResults.Tables[0].Rows[0]["Storylines"] + "' wrt='" + dsResults.Tables[0].Rows[0]["Writer"] + "' art='" + dsResults.Tables[0].Rows[0]["Artist"] + "' cd='" + Convert.ToDateTime(dsResults.Tables[0].Rows[0]["CoverDate"]).ToString("MMM yyyy") + "' noimage='1'/></a>";
                }
                catch (Exception ex)
                {
                    img = "<a href='#'><img id='img" + issue + "' src='../Images/noimage.png' height='120px' width='90px' onclick=showDetails(this) border='0' cn=\"" + dsResults.Tables[0].Rows[0]["Title"] + "\" issue='" + issue + "' cp='" + dsResults.Tables[0].Rows[0]["CoverPrice"] + "' sl='" + dsResults.Tables[0].Rows[0]["Storylines"] + "' wrt='" + dsResults.Tables[0].Rows[0]["Writer"] + "' art='" + dsResults.Tables[0].Rows[0]["Artist"] + "' cd='" + Convert.ToDateTime(dsResults.Tables[0].Rows[0]["CoverDate"]).ToString("MMM yyyy") + "' noimage='1'/></a>";
                }


                tblDetails = "<table width='100%'>";
                tblDetails += "<tr>";
                tblDetails += "<td width='20%'>" + img + "<br /><span class='spnDetails'><a href='#' onclick=showDetails('" + issue + "')>Click here for details</a></span></td>";
                tblDetails += "<td width='80%'>";

                if (dsResults.Tables.Count > 2 && dsResults.Tables[2].Rows.Count > 0 && dsResults.Tables[2].Rows[0][0] != System.DBNull.Value)
                    discount = Convert.ToDouble(dsResults.Tables[2].Rows[0][0]);

                tblDetails += GetPricingTable(dsResults.Tables[1], discount, cid, issue);

                tblDetails += "</td>";
                tblDetails += "</tr>";

                tblDetails += "</table>";
            }

            return tblDetails;
        }

        private static string GetPricingTable(DataTable dtPricing, double discount, string comicId, string issue)
        {
            string tblPricing = "";
            double sellPrice, discountPrice;
            Dictionary<string, Dictionary<string, Dictionary<string, string>>> cartData = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies["cart"].Value));
            string qty;

            tblPricing = "<table width='100%' cellspacing='0'>";
            tblPricing += "<tr>";
            tblPricing += "<td class='isuDetHeading_L'>Condition</td>";

            if (discount > 0)
            {
                tblPricing += "<td class='isuDetHeading_M'>Guide Price</td>";
                tblPricing += "<td class='isuDetHeading_M'>Our Price</td>";
                tblPricing += "<td class='isuDetHeading_M'>You Save</td>";
            }
            else
                tblPricing += "<td class='isuDetHeading_M'>Price</td>";

            tblPricing += "<td class='isuDetHeading_M'>Quantity</td>";
            tblPricing += "<td class='isuDetHeading_R'>Add to Cart</td>";
            tblPricing += "</tr>";

            for (int i = 0; i <= dtPricing.Rows.Count - 1; i++)
            {
                sellPrice = Convert.ToDouble(dtPricing.Rows[i]["SellingPrice"]);
                sellPrice = Pricing.CalculatePrice(sellPrice, Convert.ToInt32(dtPricing.Rows[i]["ConditionId"]));                
                discountPrice = sellPrice - (sellPrice * discount / 100);

                sellPrice = Math.Round(sellPrice, 2);
                discountPrice = Math.Round(discountPrice, 2);

                tblPricing += "<tr>";
                tblPricing += "<td class='isuDetRow_L'>" + dtPricing.Rows[i]["Name"] + "</b></td>";

                if (discount > 0)
                {
                    tblPricing += "<td class='isuDetRow_M'><del>€" + string.Format("{0:0.00}",sellPrice) + "</del></td>";
                    tblPricing += "<td class='isuDetRow_M' style='font-weight:bold;'>€" + string.Format("{0:0.00}",discountPrice) + "</td>";
                    tblPricing += "<td class='isuDetRow_M' style='color:red;'>€" + string.Format("{0:0.00}", (sellPrice - discountPrice)) + "</td>";
                }
                else
                    tblPricing += "<td class='isuDetRow_M'>€" + string.Format("{0:0.00}",sellPrice) + "</td>";

                if (cartData.ContainsKey(comicId) && cartData[comicId].ContainsKey(issue) && cartData[comicId][issue].ContainsKey(dtPricing.Rows[i]["ConditionId"].ToString()))
                    qty = cartData[comicId][issue][dtPricing.Rows[i]["ConditionId"].ToString()];
                else
                    qty = "0";

                tblPricing += "<td class='isuDetRow_M'>" + dtPricing.Rows[i]["Quantity"] + "</td>";
                tblPricing += "<td class='isuDetRow_R'><div id='divSpinner" + issue + "_" + i + "' comicId='" + comicId + "' issue=\"" + issue + "\" min='0' max='" + dtPricing.Rows[i]["Quantity"] + "' condId='" + dtPricing.Rows[i]["ConditionId"] + "' qty='" + qty + "'/></td>";                

                tblPricing += "</tr>";
            }


            tblPricing += "</table>";

            return tblPricing;
        }
    }
}